package org.spring.aicloud.util;

import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@Component
public class MinioUtil {
    @Resource
    private MinioClient minioClient;
    @Value("${minio.bucket}")
    private String bucketName;

    /**
     * 上传文件
     * @param fileName
     * @param inputStream
     * @param contentType
     * @return
     */
    public String upload(String fileName, InputStream inputStream,String contentType) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        //判断对应的桶是否存在
        boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder()
                .bucket(bucketName).build());
        //如果不存在则先创建
        if (!isExist){
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }
        minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(bucketName)
                        .object(fileName)
                        .stream(inputStream,-1,10485760)
                        .contentType(contentType)
                        .build()
        );
        String url = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
                        .bucket(bucketName)
                        .object(fileName)
                        .method(Method.GET)
                        .build());
        //将minio返回的url中的授权信息接去掉
        //只保留文件的地址
        //这样访问图片就没有时间限制了
        //默认的访问时限是一周
        //同时还要在minio中将对应桶的Access Policy设置为public
        String substring = url.substring(0, url.indexOf("?"));
        return substring;
    }
}
